<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天气泡管理器测试</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .test-container {
            max-width: 800px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.1);
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }
        
        .test-controls {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .test-button {
            padding: 10px 15px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            border-radius: 5px;
            color: white;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .test-button:hover {
            background: rgba(255, 255, 255, 0.3);
        }
        
        .debug-info {
            background: rgba(0, 0, 0, 0.3);
            padding: 15px;
            border-radius: 5px;
            color: white;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            white-space: pre-wrap;
            margin-top: 20px;
        }
        
        .entity-simulator {
            position: fixed;
            width: 20px;
            height: 20px;
            background: #ff6b6b;
            border-radius: 50%;
            border: 2px solid white;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .entity-simulator:hover {
            transform: scale(1.2);
        }
        
        .entity-simulator.cow {
            background: #8B4513;
        }
        
        .entity-simulator.pig {
            background: #FFC0CB;
        }
        
        .entity-simulator.chicken {
            background: #FFFF00;
        }
    </style>
</head>
<body>
    <div class="test-container">
        <h1 style="color: white; text-align: center;">聊天气泡管理器测试</h1>
        
        <div class="test-controls">
            <button class="test-button" onclick="testShortMessage()">短消息测试</button>
            <button class="test-button" onclick="testLongMessage()">长消息测试</button>
            <button class="test-button" onclick="testVeryLongMessage()">超长消息测试</button>
            <button class="test-button" onclick="testMultipleBubbles()">多气泡测试</button>
            <button class="test-button" onclick="testDistanceScaling()">距离缩放测试</button>
            <button class="test-button" onclick="clearAllBubbles()">清除所有气泡</button>
            <button class="test-button" onclick="toggleDebugInfo()">调试信息</button>
        </div>
        
        <div id="debugInfo" class="debug-info" style="display: none;"></div>
    </div>

    <!-- 模拟实体 -->
    <div class="entity-simulator cow" id="entity1" style="top: 200px; left: 200px;" title="牛"></div>
    <div class="entity-simulator pig" id="entity2" style="top: 300px; left: 400px;" title="猪"></div>
    <div class="entity-simulator chicken" id="entity3" style="top: 150px; left: 600px;" title="鸡"></div>

    <script type="module">
        // 模拟必要的依赖
        class MockEntity {
            constructor(id, type, position) {
                this.id = id;
                this.type = type;
                this.position = position;
            }
            
            getId() { return this.id; }
            getType() { return this.type; }
            getPosition() { return this.position; }
        }

        // 模拟THREE.js相机
        class MockCamera {
            constructor() {
                this.position = { x: 0, y: 0, z: 0 };
                this.rotation = { x: 0, y: 0, z: 0 };
            }
        }

        // 简化的ChatBubbleManager实现用于测试
        class ChatBubbleManager {
            constructor() {
                this.bubbles = new Map();
                this.container = null;
                this.camera = null;
                this.defaultDuration = 3000;
                this.maxDistance = 20;
                this.minScale = 0.5;
                this.maxBubbleWidth = 250;
                this.createContainer();
                this.addStyles();
            }

            createContainer() {
                this.container = document.createElement('div');
                this.container.id = 'chat-bubbles-container';
                this.container.className = 'chat-bubbles-container';
                document.body.appendChild(this.container);
            }

            addStyles() {
                const style = document.createElement('style');
                style.textContent = `
                    .chat-bubbles-container {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        pointer-events: none;
                        z-index: 100;
                    }
                    
                    .chat-bubble {
                        position: absolute;
                        background: rgba(0, 0, 0, 0.85);
                        color: white;
                        padding: 10px 14px;
                        border-radius: 16px;
                        font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
                        font-size: 14px;
                        max-width: 250px;
                        word-wrap: break-word;
                        word-break: break-word;
                        text-align: left;
                        border: 2px solid rgba(255, 255, 255, 0.3);
                        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
                        transform: translate(-50%, -100%);
                        animation: chatBubbleAppear 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
                        line-height: 1.4;
                        white-space: pre-wrap;
                        backdrop-filter: blur(4px);
                    }
                    
                    .chat-bubble::after {
                        content: '';
                        position: absolute;
                        top: 100%;
                        left: 50%;
                        transform: translateX(-50%);
                        border: 10px solid transparent;
                        border-top-color: rgba(0, 0, 0, 0.85);
                        filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
                    }
                    
                    .chat-bubble.fade-out {
                        animation: chatBubbleFadeOut 0.6s ease-in forwards;
                    }
                    
                    .chat-bubble.distant {
                        opacity: 0.7;
                        transform: translate(-50%, -100%) scale(0.8);
                    }
                    
                    .chat-bubble.very-distant {
                        opacity: 0.4;
                        transform: translate(-50%, -100%) scale(0.6);
                    }
                    
                    @keyframes chatBubbleAppear {
                        0% {
                            opacity: 0;
                            transform: translate(-50%, -100%) scale(0.6) translateY(10px);
                        }
                        60% {
                            transform: translate(-50%, -100%) scale(1.05) translateY(-2px);
                        }
                        100% {
                            opacity: 1;
                            transform: translate(-50%, -100%) scale(1) translateY(0);
                        }
                    }
                    
                    @keyframes chatBubbleFadeOut {
                        0% {
                            opacity: 1;
                            transform: translate(-50%, -100%) scale(1);
                        }
                        100% {
                            opacity: 0;
                            transform: translate(-50%, -100%) scale(0.8) translateY(-10px);
                        }
                    }
                    
                    .chat-bubble.long-text {
                        max-width: 300px;
                        font-size: 13px;
                        line-height: 1.3;
                    }
                    
                    .chat-bubble.very-long-text {
                        max-width: 350px;
                        font-size: 12px;
                        line-height: 1.2;
                        max-height: 120px;
                        overflow-y: auto;
                    }
                `;
                document.head.appendChild(style);
            }

            showBubble(entity, message, duration) {
                const bubbleId = entity.getId();
                
                if (this.bubbles.has(bubbleId)) {
                    this.removeBubble(bubbleId);
                }

                const element = this.createBubbleElement(message);
                const bubble = {
                    id: bubbleId,
                    entity,
                    message,
                    element,
                    startTime: Date.now(),
                    duration: duration || this.defaultDuration,
                    isVisible: true
                };

                this.container.appendChild(element);
                this.bubbles.set(bubbleId, bubble);
                this.updateBubblePosition(bubble);

                setTimeout(() => {
                    this.removeBubble(bubbleId);
                }, bubble.duration);
            }

            createBubbleElement(message) {
                const element = document.createElement('div');
                element.className = 'chat-bubble';
                
                const textLength = message.length;
                if (textLength > 100) {
                    element.classList.add('very-long-text');
                } else if (textLength > 50) {
                    element.classList.add('long-text');
                }
                
                const processedMessage = this.processMessageText(message);
                element.textContent = processedMessage;
                return element;
            }

            processMessageText(message) {
                if (message.length <= 30) {
                    return message;
                }

                const sentences = message.split(/([。！？.!?])/);
                let result = '';
                let currentLine = '';

                for (let i = 0; i < sentences.length; i += 2) {
                    const sentence = sentences[i] + (sentences[i + 1] || '');
                    
                    if (currentLine.length + sentence.length > 25) {
                        if (currentLine) {
                            result += currentLine + '\n';
                            currentLine = sentence;
                        } else {
                            result += sentence + '\n';
                        }
                    } else {
                        currentLine += sentence;
                    }
                }
                
                if (currentLine) {
                    result += currentLine;
                }

                return result.trim();
            }

            updateBubblePosition(bubble) {
                const entityPos = bubble.entity.getPosition();
                const entityElement = document.getElementById(bubble.entity.getId());
                
                if (entityElement) {
                    const rect = entityElement.getBoundingClientRect();
                    bubble.element.style.left = `${rect.left + rect.width / 2}px`;
                    bubble.element.style.top = `${rect.top - 20}px`;
                    bubble.element.style.display = 'block';
                }
            }

            removeBubble(bubbleId) {
                const bubble = this.bubbles.get(bubbleId);
                if (!bubble) return;

                bubble.element.classList.add('fade-out');
                bubble.isVisible = false;
                
                setTimeout(() => {
                    if (bubble.element.parentNode) {
                        bubble.element.parentNode.removeChild(bubble.element);
                    }
                    this.bubbles.delete(bubbleId);
                }, 600);
            }

            clear() {
                for (const bubbleId of this.bubbles.keys()) {
                    this.removeBubble(bubbleId);
                }
            }

            getDebugInfo() {
                return {
                    activeBubbles: Array.from(this.bubbles.values()).filter(b => b.isVisible).length,
                    totalBubbles: this.bubbles.size,
                    maxDistance: this.maxDistance,
                    defaultDuration: this.defaultDuration,
                    bubbles: Array.from(this.bubbles.values()).map(bubble => ({
                        entityId: bubble.id,
                        entityType: bubble.entity.getType(),
                        message: bubble.message.substring(0, 30) + (bubble.message.length > 30 ? '...' : ''),
                        elapsed: Date.now() - bubble.startTime,
                        duration: bubble.duration,
                        isVisible: bubble.isVisible
                    }))
                };
            }
        }

        // 创建管理器实例
        const chatBubbleManager = new ChatBubbleManager();

        // 创建模拟实体
        const entities = [
            new MockEntity('entity1', '牛', { x: 200, y: 0, z: 200 }),
            new MockEntity('entity2', '猪', { x: 400, y: 0, z: 300 }),
            new MockEntity('entity3', '鸡', { x: 600, y: 0, z: 150 })
        ];

        // 测试函数
        window.testShortMessage = () => {
            const entity = entities[0];
            chatBubbleManager.showBubble(entity, "哞~你好！", 3000);
        };

        window.testLongMessage = () => {
            const entity = entities[1];
            chatBubbleManager.showBubble(entity, "哼哼~今天天气真不错呢！我在这里找到了很多好吃的东西。", 4000);
        };

        window.testVeryLongMessage = () => {
            const entity = entities[2];
            chatBubbleManager.showBubble(entity, "咯咯咯~你知道吗？我今天早上看到了一只非常奇怪的虫子，它有着彩色的翅膀，在阳光下闪闪发光。我试图抓住它，但它飞得太快了！不过没关系，我还找到了很多其他好吃的虫子和种子。生活真是美好啊！", 6000);
        };

        window.testMultipleBubbles = () => {
            entities.forEach((entity, index) => {
                setTimeout(() => {
                    const messages = [
                        "哞~大家好！",
                        "哼哼~我也要说话！",
                        "咯咯咯~不要忘记我！"
                    ];
                    chatBubbleManager.showBubble(entity, messages[index], 4000);
                }, index * 500);
            });
        };

        window.testDistanceScaling = () => {
            // 这个测试在简化版本中不会有实际的缩放效果
            // 但可以测试基本的显示功能
            entities.forEach((entity, index) => {
                chatBubbleManager.showBubble(entity, `我在${index === 0 ? '近处' : index === 1 ? '中等距离' : '远处'}`, 3000);
            });
        };

        window.clearAllBubbles = () => {
            chatBubbleManager.clear();
        };

        let debugVisible = false;
        window.toggleDebugInfo = () => {
            debugVisible = !debugVisible;
            const debugElement = document.getElementById('debugInfo');
            debugElement.style.display = debugVisible ? 'block' : 'none';
            
            if (debugVisible) {
                updateDebugInfo();
                // 每秒更新调试信息
                window.debugInterval = setInterval(updateDebugInfo, 1000);
            } else {
                clearInterval(window.debugInterval);
            }
        };

        function updateDebugInfo() {
            const debugInfo = chatBubbleManager.getDebugInfo();
            document.getElementById('debugInfo').textContent = JSON.stringify(debugInfo, null, 2);
        }

        // 点击实体显示气泡
        entities.forEach(entity => {
            const element = document.getElementById(entity.getId());
            element.addEventListener('click', () => {
                const messages = {
                    '牛': ['哞~你好！', '哞~今天天气不错', '哞~我饿了'],
                    '猪': ['哼哼~', '哼哼~泥巴真舒服', '哼哼~有吃的吗？'],
                    '鸡': ['咯咯咯~', '咯咯咯~找虫子', '咯咯咯~下蛋了']
                };
                const entityMessages = messages[entity.getType()];
                const randomMessage = entityMessages[Math.floor(Math.random() * entityMessages.length)];
                chatBubbleManager.showBubble(entity, randomMessage, 3000);
            });
        });

        console.log('聊天气泡管理器测试页面已加载');
        console.log('点击按钮或实体来测试不同功能');
    </script>
</body>
</html>